# coding=utf-8
# !/usr/bin/python

"""

作者 丢丢喵推荐 🚓 内容均从互联网收集而来 仅供交流学习使用 版权归原创者所有 如侵犯了您的权益 请通知作者 将及时删除侵权内容
                    ====================Diudiumiao====================

"""

from Crypto.Util.Padding import unpad
from Crypto.Util.Padding import pad
from urllib.parse import unquote
from Crypto.Cipher import ARC4
from urllib.parse import quote
from base.spider import Spider
from Crypto.Cipher import AES
from datetime import datetime
from bs4 import BeautifulSoup
from base64 import b64decode
import urllib.request
import urllib.parse
import datetime
import binascii
import requests
import base64
import json
import time
import sys
import re
import os

sys.path.append('..')

xurl = "https://fz.sld.tw"

xurl1 = "https://api.cenguigui.cn"

headerx = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.87 Safari/537.36'
          }

class Spider(Spider):
    global xurl
    global xurl1
    global headerx

    def getName(self):
        return "首页"

    def init(self, extend):
        pass

    def isVideoFormat(self, url):
        pass

    def manualVideoCheck(self):
        pass

    def extract_middle_text(self, text, start_str, end_str, pl, start_index1: str = '', end_index2: str = ''):
        if pl == 3:
            plx = []
            while True:
                start_index = text.find(start_str)
                if start_index == -1:
                    break
                end_index = text.find(end_str, start_index + len(start_str))
                if end_index == -1:
                    break
                middle_text = text[start_index + len(start_str):end_index]
                plx.append(middle_text)
                text = text.replace(start_str + middle_text + end_str, '')
            if len(plx) > 0:
                purl = ''
                for i in range(len(plx)):
                    matches = re.findall(start_index1, plx[i])
                    output = ""
                    for match in matches:
                        match3 = re.search(r'(?:^|[^0-9])(\d+)(?:[^0-9]|$)', match[1])
                        if match3:
                            number = match3.group(1)
                        else:
                            number = 0
                        if 'http' not in match[0]:
                            output += f"#{match[1]}${number}{xurl}{match[0]}"
                        else:
                            output += f"#{match[1]}${number}{match[0]}"
                    output = output[1:]
                    purl = purl + output + "$$$"
                purl = purl[:-3]
                return purl
            else:
                return ""
        else:
            start_index = text.find(start_str)
            if start_index == -1:
                return ""
            end_index = text.find(end_str, start_index + len(start_str))
            if end_index == -1:
                return ""

        if pl == 0:
            middle_text = text[start_index + len(start_str):end_index]
            return middle_text.replace("\\", "")

        if pl == 1:
            middle_text = text[start_index + len(start_str):end_index]
            matches = re.findall(start_index1, middle_text)
            if matches:
                jg = ' '.join(matches)
                return jg

        if pl == 2:
            middle_text = text[start_index + len(start_str):end_index]
            matches = re.findall(start_index1, middle_text)
            if matches:
                new_list = [f'{item}' for item in matches]
                jg = '$$$'.join(new_list)
                return jg

    def homeContent(self, filter):  
        result = {}
        result = {"class": [
            {"type_id": "推荐榜", "type_name": "推荐榜"},
            {"type_id": "新剧", "type_name": "新剧"},
            {"type_id": "逆袭", "type_name": "逆袭"},
            {"type_id": "霸总", "type_name": "霸总"},
            {"type_id": "现代言情", "type_name": "现代言情"},
            {"type_id": "打脸虐渣", "type_name": "打脸虐渣"},
            {"type_id": "豪门恩怨", "type_name": "豪门恩怨"},
            {"type_id": "神豪", "type_name": "神豪"},
            {"type_id": "马甲", "type_name": "马甲"},
            {"type_id": "都市日常", "type_name": "都市日常"},
            {"type_id": "战神归来", "type_name": "战神归来"},
            {"type_id": "小人物", "type_name": "小人物"},
            {"type_id": "女性成长", "type_name": "女性成长"},
            {"type_id": "大女主", "type_name": "大女主"},
            {"type_id": "穿越", "type_name": "穿越"},
            {"type_id": "都市修仙", "type_name": "都市修仙"},
            {"type_id": "强者回归", "type_name": "强者回归"},
            {"type_id": "亲情", "type_name": "亲情"},
            {"type_id": "古装", "type_name": "古装"},
            {"type_id": "重生", "type_name": "重生"},
            {"type_id": "闪婚", "type_name": "闪婚"},
            {"type_id": "赘婿逆袭", "type_name": "赘婿逆袭"},
            {"type_id": "虐恋", "type_name": "虐恋"},
            {"type_id": "追妻", "type_name": "追妻"},
            {"type_id": "天下无敌", "type_name": "天下无敌"},
            {"type_id": "家庭伦理", "type_name": "家庭伦理"},
            {"type_id": "萌宝", "type_name": "萌宝"},
            {"type_id": "古风权谋", "type_name": "古风权谋"},
            {"type_id": "职场", "type_name": "职场"},
            {"type_id": "奇幻脑洞", "type_name": "奇幻脑洞"},
            {"type_id": "异能", "type_name": "异能"},
            {"type_id": "无敌神医", "type_name": "无敌神医"},
            {"type_id": "古风言情", "type_name": "古风言情"},
            {"type_id": "传承觉醒", "type_name": "传承觉醒"},
            {"type_id": "现言甜宠", "type_name": "现言甜宠"},
            {"type_id": "奇幻爱情", "type_name": "奇幻爱情"},
            {"type_id": "乡村", "type_name": "乡村"},
            {"type_id": "历史古代", "type_name": "历史古代"},
            {"type_id": "王妃", "type_name": "王妃"},
            {"type_id": "高手下山", "type_name": "高手下山"},
            {"type_id": "娱乐圈", "type_name": "娱乐圈"},
            {"type_id": "强强联合", "type_name": "强强联合"},
            {"type_id": "破镜重圆", "type_name": "破镜重圆"},
            {"type_id": "暗恋成真", "type_name": "暗恋成真"},
            {"type_id": "民国", "type_name": "民国"},
            {"type_id": "欢喜冤家", "type_name": "欢喜冤家"},
            {"type_id": "系统", "type_name": "系统"},
            {"type_id": "真假千金", "type_name": "真假千金"},
            {"type_id": "龙王", "type_name": "龙王"},
            {"type_id": "校园", "type_name": "校园"},
            {"type_id": "穿书", "type_name": "穿书"},
            {"type_id": "女帝", "type_name": "女帝"},
            {"type_id": "团宠", "type_name": "团宠"},
            {"type_id": "年代爱情", "type_name": "年代爱情"},
            {"type_id": "玄幻仙侠", "type_name": "玄幻仙侠"},
            {"type_id": "青梅竹马", "type_name": "青梅竹马"},
            {"type_id": "悬疑推理", "type_name": "悬疑推理"},
            {"type_id": "皇后", "type_name": "皇后"},
            {"type_id": "替身", "type_name": "替身"},
            {"type_id": "大叔", "type_name": "大叔"},
            {"type_id": "喜剧", "type_name": "喜剧"},
            {"type_id": "剧情", "type_name": "剧情"}],
            }

        return result

    def homeVideoContent(self):
        pass

    def build_category_url(self, cid, page):
        return f'{xurl1}/api/duanju/api.php?classname={cid}&offset={str(page)}&showRawParams=false'

    def fetch_category_data(self, url):
        detail = requests.get(url=url, headers=headerx)
        detail.encoding = "utf-8"
        return detail.json()

    def parse_video_info(self, vod):
        name = vod['title']
        id = vod['book_id']
        pic = vod['cover']
        remark = vod['sub_title']
        return {
            "vod_id": id,
            "vod_name": name,
            "vod_pic": pic,
            "vod_remarks": '' + remark
               }

    def build_video_list(self, data):
        videos = []
        for vod in data['data']:
            video = self.parse_video_info(vod)
            videos.append(video)
        return videos

    def build_result_structure(self, videos, page):
        result = {'list': videos}
        result['page'] = page
        result['pagecount'] = 9999
        result['limit'] = 90
        result['total'] = 999999
        return result

    def categoryContent(self, cid, pg, filter, ext):
        page = int(pg) if pg else 1
        url = self.build_category_url(cid, page)
        data = self.fetch_category_data(url)
        videos = self.build_video_list(data)
        result = self.build_result_structure(videos, pg)
        return result

    def build_detail_url(self, did):
        return f'{xurl1}/api/duanju/api.php?book_id={did}&showRawParams=false'

    def fetch_detail_data(self, url):
        detail = requests.get(url=url, headers=headerx)
        detail.encoding = "utf-8"
        return detail.json()

    def parse_basic_info(self, data):
        return {
            "content": '' + data['desc'],
            "director": data['book_name'],
            "actor": data['author'],
            "remarks": data['duration'],
            "year": data['time']
               }

    def build_play_urls(self, data):
        bofang = ''
        for sou in data['data']:
            id = sou['video_id']
            name = sou['title']
            bofang = bofang + name + '$' + id + '#'
        return bofang[:-1] if bofang else ''

    def create_video_entry(self, did, basic_info, play_urls):
        return {
            "vod_id": did,
            "vod_director": basic_info["director"],
            "vod_actor": basic_info["actor"],
            "vod_remarks": basic_info["remarks"],
            "vod_year": basic_info["year"],
            "vod_content": basic_info["content"],
            "vod_play_from": '短剧专线',
            "vod_play_url": play_urls
              }

    def detailContent(self, ids):
        did = ids[0]
        result = {}
        videos = []
        url = self.build_detail_url(did)
        data = self.fetch_detail_data(url)
        basic_info = self.parse_basic_info(data)
        play_urls = self.build_play_urls(data)
        video_entry = self.create_video_entry(did, basic_info, play_urls)
        videos.append(video_entry)
        result['list'] = videos
        return result

    def build_player_url(self, id):
        return f'{xurl1}/api/duanju/api.php?video_id={id}&type=mp4&level=1080p '

    def fetch_redirect_url(self, url):
        response = requests.get(url=url, headers=headerx, allow_redirects=False)
        return response.headers.get('Location')

    def build_player_result(self, url):
        result = {}
        result["parse"] = 0
        result["playUrl"] = ''
        result["url"] = url
        result["header"] = headerx
        return result

    def playerContent(self, flag, id, vipFlags):
        request_url = self.build_player_url(id)
        redirect_url = self.fetch_redirect_url(request_url)
        result = self.build_player_result(redirect_url)
        return result

    def build_search_url(self, key, page):
        return f'{xurl1}/api/duanju/api.php?name={key}&page={str(page)}&showRawParams=false'

    def fetch_search_data(self, url):
        detail = requests.get(url=url, headers=headerx)
        detail.encoding = "utf-8"
        return detail.json()

    def parse_search_result(self, vod):
        return {
            "vod_id": vod['book_id'],
            "vod_name": vod['title'],
            "vod_pic": vod['cover'],
            "vod_remarks": '' + vod['type']
               }

    def build_search_list(self, data):
        videos = []
        for vod in data['data']:
            video = self.parse_search_result(vod)
            videos.append(video)
        return videos

    def build_search_result_structure(self, videos, pg):
        result = {}
        result['list'] = videos
        result['page'] = pg
        result['pagecount'] = 9999
        result['limit'] = 90
        result['total'] = 999999
        return result

    def searchContentPage(self, key, quick, pg):
        page = int(pg) if pg else 1
        url = self.build_search_url(key, page)
        data = self.fetch_search_data(url)
        videos = self.build_search_list(data)
        result = self.build_search_result_structure(videos, pg)
        return result

    def searchContent(self, key, quick, pg="1"):
        return self.searchContentPage(key, quick, '1')

    def localProxy(self, params):
        if params['type'] == "m3u8":
            return self.proxyM3u8(params)
        elif params['type'] == "media":
            return self.proxyMedia(params)
        elif params['type'] == "ts":
            return self.proxyTs(params)
        return None










